<template>
  <div class="recharge-page">
    <!-- 余额和会员等级卡片 -->
    <div class="balance-card-container">
      <el-card class="balance-card">
        <template #header>
          <div class="card-header">
            <el-icon><Wallet /></el-icon>
            <span>账户余额</span>
          </div>
        </template>
        
        <div class="balance-info" v-if="balanceInfo">
          <div class="balance-amount">
            <span class="currency">¥</span>
            <span class="amount">{{ balanceInfo.balance || '0.00' }}</span>
          </div>
          
          <div class="balance-details">
            <div class="detail-item">
              <span class="label">可用余额：</span>
              <span class="value">¥{{ balanceInfo.availableBalance || '0.00' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">冻结余额：</span>
              <span class="value">¥{{ balanceInfo.frozenBalance || '0.00' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">累计充值：</span>
              <span class="value">¥{{ balanceInfo.totalRecharge || '0.00' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">累计消费：</span>
              <span class="value">¥{{ balanceInfo.totalConsume || '0.00' }}</span>
            </div>
          </div>
        </div>
        
        <div class="loading-placeholder" v-else-if="loading">
          <el-skeleton :rows="3" animated />
        </div>
      </el-card>

      <el-card class="member-card">
        <template #header>
          <div class="card-header">
                            <el-icon><Trophy /></el-icon>
            <span>会员等级</span>
          </div>
        </template>
        
        <div class="member-info" v-if="userInfo">
          <div class="member-level">
            <el-tag 
              :type="getMemberLevelType(userInfo.memberLevel)" 
              size="large"
              class="member-tag"
            >
              {{ getMemberLevelName(userInfo.memberLevel) }}
            </el-tag>
          </div>
          
          <div class="member-progress" v-if="userInfo.memberLevel !== 'VIP1'">
            <div class="progress-info">
              <span class="next-level">{{ getNextLevelInfo() }}</span>
            </div>
            <el-progress 
              :percentage="getMemberProgress()" 
              :status="getProgressStatus()"
              :stroke-width="8"
            />
            <div class="progress-text">
              还需充值 ¥{{ getNeededAmount() }} 升级到{{ getNextLevelName() }}
            </div>
          </div>
          
          <div class="member-benefits" v-else>
            <div class="vip-badge">
              <el-icon><Medal /></el-icon>
              <span>恭喜您已达到最高等级！</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 充值卡片 -->
    <el-card class="recharge-card">
      <template #header>
        <div class="card-header">
          <el-icon><CreditCard /></el-icon>
          <span>账户充值</span>
        </div>
      </template>
      
      <el-form 
        :model="rechargeForm" 
        :rules="rechargeRules" 
        ref="rechargeFormRef"
        label-width="120px"
        class="recharge-form"
      >
        <el-form-item label="充值金额" prop="rechargeAmount">
          <el-input
            v-model="rechargeForm.rechargeAmount"
            type="number"
            placeholder="请输入充值金额"
            :min="0.01"
            :step="0.01"
            class="amount-input"
          >
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="快捷金额">
          <div class="quick-amounts">
            <el-button
              v-for="amount in quickAmounts"
              :key="amount"
              @click="setQuickAmount(amount)"
              size="small"
              :type="rechargeForm.rechargeAmount == amount.toString() ? 'primary' : ''"
              :plain="rechargeForm.rechargeAmount != amount.toString()"
            >
              ¥{{ amount }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-radio-group v-model="rechargeForm.paymentMethod">
            <el-radio value="BALANCE">余额充值（模拟）</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="rechargeForm.remark"
            placeholder="请输入充值备注（可选）"
            :maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleRecharge"
            :loading="submitLoading"
            size="large"
            class="recharge-btn"
          >
            <el-icon><CreditCard /></el-icon>
            立即充值
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Wallet, Trophy, CreditCard, Medal } from '@element-plus/icons-vue'
import request from '../utils/request'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const balanceInfo = ref(null)
const userInfo = ref(null)
const rechargeFormRef = ref()

// 快捷充值金额
const quickAmounts = [10, 50, 100, 200, 500, 1000]

// 充值表单
const rechargeForm = reactive({
  rechargeAmount: '',
  paymentMethod: 'BALANCE',
  remark: ''
})

// 表单验证规则
const rechargeRules = {
  rechargeAmount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value || parseFloat(value) <= 0) {
          callback(new Error('充值金额必须大于0'))
        } else if (parseFloat(value) > 100000) {
          callback(new Error('单次充值金额不能超过100,000元'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

// 获取用户余额信息
const fetchBalanceInfo = async () => {
  try {
    loading.value = true
    const response = await request.get('/user/balance/my')
    balanceInfo.value = response.data
  } catch (error) {
    console.error('获取余额信息失败:', error)
    ElMessage.error('获取余额信息失败')
  } finally {
    loading.value = false
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await request.get('/user/info')
    userInfo.value = response.data
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 设置快捷金额
const setQuickAmount = (amount) => {
  rechargeForm.rechargeAmount = amount.toString()
  // 手动触发表单验证
  nextTick(() => {
    rechargeFormRef.value?.validateField('rechargeAmount')
  })
}

// 获取会员等级名称
const getMemberLevelName = (level) => {
  if (!level || level === 'NORMAL') return '普通用户'
  switch (level) {
    case 'VIP3': return '三级会员'
    case 'VIP2': return '二级会员'
    case 'VIP1': return '一级会员'
    default: return '普通用户'
  }
}

// 获取会员等级标签类型
const getMemberLevelType = (level) => {
  if (!level || level === 'NORMAL') return 'info'
  switch (level) {
    case 'VIP3': return 'warning'
    case 'VIP2': return 'success'
    case 'VIP1': return 'danger'
    default: return 'info'
  }
}

// 获取下一等级信息
const getNextLevelInfo = () => {
  if (!userInfo.value) return ''
  const level = userInfo.value.memberLevel || 'NORMAL'
  
  switch (level) {
    case 'NORMAL': return '距离三级会员'
    case 'VIP3': return '距离二级会员'
    case 'VIP2': return '距离一级会员'
    default: return ''
  }
}

// 获取下一等级名称
const getNextLevelName = () => {
  if (!userInfo.value) return ''
  const level = userInfo.value.memberLevel || 'NORMAL'
  
  switch (level) {
    case 'NORMAL': return '三级会员'
    case 'VIP3': return '二级会员'
    case 'VIP2': return '一级会员'
    default: return ''
  }
}

// 获取需要的充值金额
const getNeededAmount = () => {
  if (!balanceInfo.value || !userInfo.value) return '0'
  
  const totalRecharge = parseFloat(balanceInfo.value.totalRecharge || 0)
  const level = userInfo.value.memberLevel || 'NORMAL'
  
  switch (level) {
    case 'NORMAL': return Math.max(0, 500 - totalRecharge).toFixed(2)
    case 'VIP3': return Math.max(0, 800 - totalRecharge).toFixed(2)
    case 'VIP2': return Math.max(0, 1000 - totalRecharge).toFixed(2)
    default: return '0'
  }
}

// 获取会员进度百分比
const getMemberProgress = () => {
  if (!balanceInfo.value || !userInfo.value) return 0
  
  const totalRecharge = parseFloat(balanceInfo.value.totalRecharge || 0)
  const level = userInfo.value.memberLevel || 'NORMAL'
  
  let currentThreshold = 0
  let nextThreshold = 500
  
  switch (level) {
    case 'NORMAL':
      currentThreshold = 0
      nextThreshold = 500
      break
    case 'VIP3':
      currentThreshold = 500
      nextThreshold = 800
      break
    case 'VIP2':
      currentThreshold = 800
      nextThreshold = 1000
      break
    default:
      return 100
  }
  
  const progress = ((totalRecharge - currentThreshold) / (nextThreshold - currentThreshold)) * 100
  return Math.min(100, Math.max(0, progress))
}

// 获取进度条状态
const getProgressStatus = () => {
  const progress = getMemberProgress()
  if (progress >= 100) return 'success'
  if (progress >= 80) return 'warning'
  return ''
}

// 处理充值
const handleRecharge = async () => {
  try {
    await rechargeFormRef.value.validate()
    
    await ElMessageBox.confirm(
      `确认充值 ¥${rechargeForm.rechargeAmount} 元吗？`,
      '确认充值',
      {
        type: 'warning',
        confirmButtonText: '确认充值',
        cancelButtonText: '取消'
      }
    )
    
    submitLoading.value = true
    
    const response = await request.post('/user/recharge', {
      rechargeAmount: parseFloat(rechargeForm.rechargeAmount),
      paymentMethod: rechargeForm.paymentMethod,
      remark: rechargeForm.remark || '用户充值'
    })
    
    ElMessage.success('充值成功！订单号：' + response.data)
    
    // 重新获取余额信息和用户信息
    await Promise.all([fetchBalanceInfo(), fetchUserInfo()])
    
    // 重置表单
    resetForm()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('充值失败:', error)
      ElMessage.error('充值失败：' + (error.response?.data?.message || error.message))
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  rechargeFormRef.value?.resetFields()
  rechargeForm.rechargeAmount = ''
  rechargeForm.remark = ''
}

// 页面加载时获取数据
onMounted(() => {
  fetchBalanceInfo()
  fetchUserInfo()
})
</script>

<style scoped>
.recharge-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.balance-card-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .balance-card-container {
    grid-template-columns: 1fr;
  }
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.card-header .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.balance-info {
  text-align: center;
}

.balance-amount {
  margin-bottom: 20px;
}

.currency {
  font-size: 20px;
  color: #666;
  margin-right: 5px;
}

.amount {
  font-size: 36px;
  font-weight: bold;
  color: #67c23a;
}

.balance-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  font-weight: 600;
  color: #333;
}

.member-info {
  text-align: center;
}

.member-level {
  margin-bottom: 20px;
}

.member-tag {
  font-size: 16px;
  padding: 8px 16px;
}

.member-progress {
  margin-top: 20px;
}

.progress-info {
  margin-bottom: 10px;
}

.next-level {
  color: #666;
  font-size: 14px;
}

.progress-text {
  margin-top: 8px;
  color: #666;
  font-size: 12px;
}

.vip-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #f56c6c;
  font-weight: 600;
  margin-top: 20px;
}

.vip-badge .el-icon {
  margin-right: 5px;
  font-size: 20px;
}

.recharge-card {
  margin-top: 20px;
}

.recharge-form {
  max-width: 600px;
  margin: 0 auto;
}

.amount-input {
  font-size: 16px;
}

.quick-amounts {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.recharge-btn {
  width: 200px;
  height: 45px;
  font-size: 16px;
}

.loading-placeholder {
  padding: 20px;
}
</style> 